package com.zjbbkj.baibai.netty.message.receive;

import com.alibaba.fastjson.TypeReference;
import com.zjbbkj.baibai.common.utils.wanli.MyUtils;
import com.zjbbkj.baibai.common.utils.wanli.RedisCacheUtil;
import com.zjbbkj.baibai.domain.device.Device;
import com.zjbbkj.baibai.netty.feign.DeviceFeignService;
import com.zjbbkj.baibai.netty.maps.ContainerMaps;
import com.zjbbkj.baibai.netty.message.factory.Operation;
import com.zjbbkj.baibai.netty.pojo.ProtocolMessage;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Map;

/**  更新ICCID
 * @author WanLi
 * @date 2021年08月24日 17:34
 */
@Slf4j
public class ReceiveAID implements Operation {

    @Resource
    private RedisCacheUtil redisCacheUtil;

    @Resource
    private DeviceFeignService deviceFeignService;


    /**
     *
     * @Description @Description //_IDAID000000020898602B3131650175846#/#CG_LED2_V0.0.1#/#CG_LED2_VA
     * @param message
     * @param channel
     */
    @Override
    public void parsingMsg(String message, Channel channel) {
        Map<Channel, String> channelsX = ContainerMaps.getChannelsX();
        try{
            if (channelsX.containsKey(channel)) {
                String IMEIID = channelsX.get(channel);
                updateDevice(IMEIID, message);
            }
        }catch (Exception e){
            log.info(e.getMessage());
        }
    }


    public void updateDevice(String IMEIID, String cmd) {
        //更新库

        Device device = deviceFeignService.getDevice(IMEIID).getData("device",new TypeReference<Device>(){});
        if (!MyUtils.isNull(device)) {

            String[] str = cmd.split("#/#");
            String ICCID = str[0].substring(15);
            String deviceSoftwareVersion = str[1];
            String deviceHardwareVersion = str[2];
            device.setDeviceIccid(ICCID);
            device.setDeviceSoftwareVersion(deviceSoftwareVersion);
            device.setDeviceHardwareVersion(deviceHardwareVersion);
            deviceFeignService.updateDevice(device);

            //更新缓存的数据
            ProtocolMessage p =  (ProtocolMessage)redisCacheUtil.get(IMEIID);
            p.setIccid(ICCID);
            p.setDeviceOta("0");
            p.setDeviceSoftwareVersion(deviceSoftwareVersion);
            p.setDeviceHardwareVersion(deviceHardwareVersion);
            redisCacheUtil.set(IMEIID,p);
        }
    }
}
